package com.ruoyi.project.channel.channelAccountAmount.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.channelAccount.domain.ChannelAccount;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.payerPayType.domain.PayerPayType;
import com.ruoyi.project.channel.payerPayType.service.IPayerPayTypeService;
import com.ruoyi.project.pay.PayServiceImpl;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.channel.channelAccountAmount.domain.ChannelAccountAmount;
import com.ruoyi.project.channel.channelAccountAmount.service.IChannelAccountAmountService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 个码预充值信息操作处理
 *
 * @author CAIN
 * @date 2019-09-06
 */
@Controller
@RequestMapping("/channel/channelAccountAmount")
public class ChannelAccountAmountController extends BaseController {
    private String prefix = "channel/channelAccountAmount";
    @Autowired
    private PayServiceImpl payService;
    @Autowired
    private IChannelAccountAmountService channelAccountAmountService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IChannelAccountService channelAccountService;
    @Autowired
    private IPayerPayTypeService payerPayTypeService;

    @RequiresPermissions("channel:channelAccountAmount:view")
    @GetMapping()
    public String channelAccountAmount(ModelMap mmap) {
        PayerPayType search = new PayerPayType();
        search.setPayerUserName("系统自带");
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(search);
        mmap.put("payerPayTypes", payerPayTypes);
        mmap.put("channels", userService.selectChannelList(new User()));
        return prefix + "/channelAccountAmount";
    }

    /**
     * 查询个码预充值列表
     */
    @RequiresPermissions("channel:channelAccountAmount:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ChannelAccountAmount channelAccountAmount) {
        startPage();

        // 取身份信息
        User user = getSysUser();
        String roleKey = ShiroUtils.getSysUser().getRoles().get(0).getRoleKey();
        if (!roleKey.equals("admin")&& !roleKey.equals("admin2")) {
            channelAccountAmount.setChannelUserId(user.getUserId());
        }

        List<ChannelAccountAmount> list = channelAccountAmountService.selectChannelAccountAmountList(channelAccountAmount);
        return getDataTable(list);
    }


    /**
     * 导出个码预充值列表
     */
    @RequiresPermissions("channel:channelAccountAmount:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ChannelAccountAmount channelAccountAmount) {
        List<ChannelAccountAmount> list = channelAccountAmountService.selectChannelAccountAmountList(channelAccountAmount);
        ExcelUtil<ChannelAccountAmount> util = new ExcelUtil<ChannelAccountAmount>(ChannelAccountAmount.class);
        return util.exportExcel(list, "channelAccountAmount");
    }

    /**
     * 新增个码预充值
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        PayerPayType search = new PayerPayType();
        search.setPayerUserName("系统自带");
        List<PayerPayType> payerPayTypes = payerPayTypeService.selectPayerPayTypeList(search);
        mmap.put("payerPayTypes", payerPayTypes);
        return prefix + "/add";
    }
    /**
     * 新增保存个码预充值
     */
    @RequiresPermissions("channel:channelAccountAmount:cashOut")
    @Log(title = "个码提现", businessType = BusinessType.INSERT)
    @PostMapping("/cashOut")
    @ResponseBody
    public AjaxResult cashOut(@RequestBody ChannelAccountAmount channelAccountAmount) {
        ChannelAccount channelAccount = channelAccountService.selectChannelAccountById(channelAccountAmount.getAccountId());
        if(channelAccount == null){
            return AjaxResult.error("找不到账号,请重新输入账号信息");
        }
        channelAccountAmount.setAccount(channelAccount.getAccount());
        channelAccountAmount.setPayType(channelAccount.getPayType());
        channelAccountAmount.setOpType("提现");
        channelAccountAmount.setAccountId(channelAccount.getAccountId());
        channelAccountAmount.setOrderStatus("1");
        channelAccountAmount.setChannelUserId(channelAccount.getChannelUserId());
        channelAccountAmount.setCreateTime(new Date());
        channelAccountAmount.setCreateBy(ShiroUtils.getLoginName());
        if(channelAccountAmount.getAmount().compareTo(channelAccount.getAmount()) == 1){
            return AjaxResult.error("提现金额大于可提现金额,请重新输入提现金额");
        }
        // 提现金额设置为 -
        channelAccountAmount.setAmount(BigDecimal.ZERO.subtract(channelAccountAmount.getAmount()));
        channelAccountAmount.setPayAmount(channelAccountAmount.getAmount());
        channelAccount.setAmount(channelAccount.getAmount().add(channelAccountAmount.getAmount()));
        channelAccountService.setAmount(channelAccount);
        return toAjax(channelAccountAmountService.insertChannelAccountAmount(channelAccountAmount));
    }
    /**
     * 新增保存个码预充值
     */
    @RequiresPermissions("channel:channelAccountAmount:add")
    @Log(title = "个码预充值", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ChannelAccountAmount channelAccountAmount) {
//        ChannelAccount search = new ChannelAccount();
//        search.setPayType(channelAccountAmount.getPayType());
//        search.setAccount(channelAccountAmount.getAccount());
//        List<ChannelAccount> channelAccounts = channelAccountService.selectChannelAccountList(search);
//        if(channelAccounts.size()==0){
//            return AjaxResult.error("找不到账号,请重新输入账号信息");
//        }
//        if(channelAccounts.size()>1){
//            return AjaxResult.error("系统账号有误,录入了多条相同账号");
//        }
//        channelAccountAmount.setAccountId(channelAccounts.get(0).getAccountId());
//        channelAccountAmount.setOrderStatus("1");
//        channelAccountAmount.setChannelUserId(channelAccounts.get(0).getChannelUserId());
//        channelAccountAmount.setCreateTime(new Date());
//        channelAccountAmount.setCreateBy(ShiroUtils.getLoginName());
//
//        if(channelAccountAmount.getOpType().equals("提现")){
//            if(channelAccountAmount.getAmount().compareTo(channelAccounts.get(0).getAmount()) == 1){
//                return AjaxResult.error("提现金额大于可提现金额,请重新输入提现金额");
//            }
//            // 提现金额设置为 -
//            channelAccountAmount.setAmount(BigDecimal.ZERO.subtract(channelAccountAmount.getAmount()));
//        }
//        channelAccountAmount.setPayAmount(channelAccountAmount.getAmount());
//        channelAccounts.get(0).setAmount(channelAccounts.get(0).getAmount().add(channelAccountAmount.getAmount()));
//        channelAccountService.setAmount(channelAccounts.get(0));
        return toAjax(channelAccountAmountService.insertChannelAccountAmount(channelAccountAmount));
    }

    /**
     * 修改个码预充值
     */
    @GetMapping("/edit/{accountCashId}")
    public String edit(@PathVariable("accountCashId") Long accountCashId, ModelMap mmap) {
        ChannelAccountAmount channelAccountAmount = channelAccountAmountService.selectChannelAccountAmountById(accountCashId);
        mmap.put("channelAccountAmount", channelAccountAmount);
        return prefix + "/edit";
    }

    /**
     * 修改保存个码预充值
     */
    @RequiresPermissions("channel:channelAccountAmount:edit")
    @Log(title = "个码预充值", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ChannelAccountAmount channelAccountAmount) {
        return toAjax(channelAccountAmountService.updateChannelAccountAmount(channelAccountAmount));
    }

    /**
     * 删除个码预充值
     */
    @RequiresPermissions("channel:channelAccountAmount:remove")
    @Log(title = "个码预充值", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(channelAccountAmountService.deleteChannelAccountAmountByIds(ids));
    }

    /**
     * 新增保存个码预充值
     */
    @RequiresPermissions("channel:channelAccountAmount:add")
    @Log(title = "充值", businessType = BusinessType.INSERT)
    @PostMapping("/order")
    @ResponseBody
    public AjaxResult addOrder(@RequestBody ChannelAccountAmount channelAccountAmount, String payType) {
        User user = userService.selectUserByLoginName("系统商户");
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(user.getUserId());
        BigDecimal amount = channelAccountAmount.getPayAmount();
        ChannelOrder channelOrder = new ChannelOrder();
        channelOrder.setBusinessId(user.getUserId());
        String keyup_prefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String keyup_append = String.valueOf(new Random().nextInt(899999) + 100000);
        String payOrderid = keyup_prefix + keyup_append;//订单号
        channelOrder.setChildOrderno(payOrderid);
        channelOrder.setAmount(amount);
        channelOrder.setPayType(payType);
        channelOrder.setTime(keyup_prefix);
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(user.getUserId());
        stringBuilder.append("&payType=").append(payType);
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&amount=").append(amount);
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        System.out.println("1111:"+stringBuilder.toString());
        String sign = Md5Utils.androidMD5(stringBuilder.toString());
        channelOrder.setSign(sign);
//        ChannelAccount channelAccount = channelAccountService.selectChannelAccountById(channelAccountAmount.getAccountId());
//        channelAccountAmount.setAccount(channelAccount.getAccount());
        channelAccountAmount.setOrderId(channelOrder.getChildOrderno());
//        channelAccountAmount.setChannelUserId(channelAccount.getChannelUserId());
        channelAccountAmount.setPayType(payType);
        channelAccountAmount.setOrderStatus("0");
        channelAccountAmount.setOpType("预充值");
        channelAccountAmount.setCreateTime(new Date());
        channelAccountAmount.setCreateBy(ShiroUtils.getLoginName());
        channelAccountAmountService.insertChannelAccountAmount(channelAccountAmount);
        return payService.addOrder(channelOrder, null);
    }

}
